package com.kiln.juxingqs.ui

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.View
import androidx.core.graphics.drawable.toBitmap
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import client.global.commlib.comm_ui.bean.Areas
import client.global.commlib.dialog.CameraOrSelectDialog
import client.global.commlib.dialog.SelectAddrDialog
import client.global.commlib.dialog.SelectShengShiAddrDialog
import client.global.commlib.toast.toast
import client.global.commlib.utils.StoreUtil
import client.global.commlib.utils.Util
import client.global.commlib.utils.listFromPath
import client.global.commlib.widget.EmptyLayout
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.Gson
import com.kiln.juxingqs.BaseMiddleActivity
import com.kiln.juxingqs.R
import com.kiln.juxingqs.api.bean.IdCardInfo
import com.kiln.juxingqs.api.bean.UserInfo
import com.kiln.juxingqs.databinding.ActivitySetskxxnewBinding
import com.kiln.juxingqs.dialog.MsgTitleDialog
import com.kiln.juxingqs.dialog.SelectDateRangeDialog
import com.kiln.juxingqs.ui.vm.SetskxxNewViewModel
import com.tencent.ocr.sdk.common.CustomConfigUi
import com.tencent.ocr.sdk.common.ISDKKitResultListener
import com.tencent.ocr.sdk.common.ISdkOcrEntityResultListener
import com.tencent.ocr.sdk.common.OcrModeType
import com.tencent.ocr.sdk.common.OcrSDKConfig
import com.tencent.ocr.sdk.common.OcrSDKKit
import com.tencent.ocr.sdk.common.OcrType
import com.tencent.ocr.sdk.entity.BankCardOcrResult
import com.tencent.ocr.sdk.entity.IdCardOcrResult
import com.tencent.ocr.sdk.entity.OcrProcessResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.util.Timer
import java.util.TimerTask

class SetSkxxNewActivity : BaseMiddleActivity<SetskxxNewViewModel, ActivitySetskxxnewBinding>() {
    override fun getLayout(): Int {
        return R.layout.activity_setskxxnew
    }

    var timerTask: TimerTask? = null
    var timer: Timer? = null
    override fun initViewModel(): SetskxxNewViewModel = createViewModel()
    override fun onDestroy() {
        timerTask?.let { it.cancel() }
        timer?.let { it.cancel() }
        super.onDestroy()
    }

    override fun initView() {
        binding.event = this

        binding.vm = viewModel

        StoreUtil.getBean<UserInfo>(this)?.let {
            viewModel.phone.value = it.phone
        }
        val secretId = "AKIDpV2LTTIvKVXcjmv007DKPNqGeu1IPWr3"
        val secretKey = "NVUG4pT1RuLgoiP7kEmU5aAymYFo9Set"

        val configBuilder: /*@@vlhvme@@*/OcrSDKConfig =
            OcrSDKConfig.newBuilder(secretId, secretKey, null)
                .setOcrType(OcrType.BankCardOCR) // 设置默认的业务识别，银行卡
                .setModeType(OcrModeType.OCR_DETECT_AUTO_MANUAL) // 自动识别模式
                .setReflectWarn(true) // 自动识别的时长ms
                .setAutoTimeout(20000)
                .setReshootWarn(true)
                .setCopyWarn(true)
                .setBorderCheckWarn(true)
                .build()
        // 初始化SDK
        // 初始化SDK
        OcrSDKKit.getInstance().initWithConfig(this, configBuilder)
    }

    override fun observerUI() {
        viewModel.codeRet.observe(this, {

            it?.apply {

                if (isSuccess) {
                    toast("获取验证码成功")

                    timerTask?.let { it.cancel() }
                    timer?.let { it.cancel() }

                    viewModel.getCodeEnable.postValue(false)

                    timerTask = object : TimerTask() {
                        var count = 60
                        override fun run() {
                            count--;
                            viewModel.getCodeTxt.postValue("${count}秒后获取")
                            if (count <= 0) {
                                viewModel.getCodeEnable.postValue(true)
                                viewModel.getCodeTxt.postValue("获取验证码")
                                timerTask!!.cancel()

                            }
                        }
                    }
                    timer = Timer().apply { schedule(timerTask, 0, 1000) }
                } else {
                    viewModel.getCodeEnable.value = true
                    viewModel.getCodeTxt.value = "获取验证码"

                }

            }
        })
        binding.emptyLayout.setOnClickListener {
            viewModel.callThree()
        }
        viewModel.dataThree.observe(this, {
            it?.let {
                if (it.isSuccess) {

                    it.data?.pay_list?.let {
                        if (it.size > 0) {
                            viewModel.realName.value = it.get(0).real_name
                            viewModel.bankName.value = it.get(0).bank_name
                            viewModel.bankCard.value = it.get(0).bank_card
                            viewModel.idcard.value = it.get(0).id_card
                            viewModel.id_card_type.value = it.get(0).id_card_type
                            viewModel.startDate.value = it.get(0).begin_date
                            viewModel.endDate.value = it.get(0).end_date
                            viewModel.phone.value = it.get(0).phone
                            viewModel.userEmail.value = it.get(0).email
                            viewModel.userAddr.value = it.get(0).detail_address
                            if (it.get(0).hfb_pay_msg.isNullOrEmpty()) {
                                binding.errMsg.visibility = View.GONE
                            } else {
                                binding.errMsg.visibility = View.VISIBLE
                                binding.errMsg.text = "失败原因：" + it.get(0).hfb_pay_msg
                            }
                            if (it.get(0).hfb_pay_msg_c.isNullOrEmpty()) {
                                binding.errMsg2.visibility = View.GONE
                            } else {
                                binding.errMsg2.visibility = View.VISIBLE
                                binding.errMsg2.text = it.get(0).hfb_pay_msg_c
                            }
                            viewModel.bankcardFontUrl.value = it.get(0).bank_front_img
                            viewModel.idcardFontUrl.value = it.get(0).id_card_front_img
                            viewModel.idcardBackUrl.value = it.get(0).id_card_back_img
                            viewModel.idcardFontHandUrl.value = it.get(0).hold_id_card_front_img
                            viewModel.bandcardBackUrl.value = it.get(0).bank_back_img
                            viewModel.bandcardHandUrl.value = it.get(0).bank_owner_hold_img
                            viewModel.bandcardHand2Url.value = it.get(0).hold_bank_front_img

                            mImgLoader.load("https://res.heepay.com" + it.get(0).bank_front_img)
                                .into(object : CustomTarget<Drawable>() {
                                    override fun onResourceReady(
                                        resource: Drawable,
                                        transition: Transition<in Drawable>?
                                    ) {
                                        viewModel.bankcardFont.value = resource.toBitmap()
                                        // 图片加载完成后的处理逻辑
                                    }

                                    override fun onLoadCleared(placeholder: Drawable?) {
                                        // 可选的清除操作
                                    }
                                })
                            mImgLoader.load("https://res.heepay.com" + it.get(0).bank_back_img)
                                .into(object : CustomTarget<Drawable>() {
                                    override fun onResourceReady(
                                        resource: Drawable,
                                        transition: Transition<in Drawable>?
                                    ) {
                                        viewModel.bandcardBack.value = resource.toBitmap()
                                        // 图片加载完成后的处理逻辑
                                    }

                                    override fun onLoadCleared(placeholder: Drawable?) {
                                        // 可选的清除操作
                                    }
                                })
                            mImgLoader.load("https://res.heepay.com" + it.get(0).bank_owner_hold_img)
                                .into(object : CustomTarget<Drawable>() {
                                    override fun onResourceReady(
                                        resource: Drawable,
                                        transition: Transition<in Drawable>?
                                    ) {
                                        viewModel.bandcardHand.value = resource.toBitmap()
                                        // 图片加载完成后的处理逻辑
                                    }

                                    override fun onLoadCleared(placeholder: Drawable?) {
                                        // 可选的清除操作
                                    }
                                })
                            mImgLoader.load("https://res.heepay.com" + it.get(0).id_card_front_img)
                                .into(object : CustomTarget<Drawable>() {
                                    override fun onResourceReady(
                                        resource: Drawable,
                                        transition: Transition<in Drawable>?
                                    ) {
                                        viewModel.idcardFont.value = resource.toBitmap()
                                        // 图片加载完成后的处理逻辑
                                    }

                                    override fun onLoadCleared(placeholder: Drawable?) {
                                        // 可选的清除操作
                                    }
                                })
                            mImgLoader.load("https://res.heepay.com" + it.get(0).id_card_back_img)
                                .into(object : CustomTarget<Drawable>() {
                                    override fun onResourceReady(
                                        resource: Drawable,
                                        transition: Transition<in Drawable>?
                                    ) {
                                        viewModel.idcardBack.value = resource.toBitmap()
                                        // 图片加载完成后的处理逻辑
                                    }

                                    override fun onLoadCleared(placeholder: Drawable?) {
                                        // 可选的清除操作
                                    }
                                })
                            mImgLoader.load("https://res.heepay.com" + it.get(0).hold_id_card_front_img)
                                .into(object : CustomTarget<Drawable>() {
                                    override fun onResourceReady(
                                        resource: Drawable,
                                        transition: Transition<in Drawable>?
                                    ) {
                                        viewModel.idcardFontHand.value = resource.toBitmap()
                                        // 图片加载完成后的处理逻辑
                                    }

                                    override fun onLoadCleared(placeholder: Drawable?) {
                                        // 可选的清除操作
                                    }
                                })

                            val input: InputStream = resources.assets.open("c_areas.json")
                            val citys = input.listFromPath<Areas>()


                            it.get(0).manage_region_code?.let { prov_id ->

                                var shengshis = ""
                                var shengshiIds = ""

                                citys?.RECORDS?.let {

                                    val sheng = prov_id.substring(0, 2) + "0000"
                                    for (c in it) {
                                        if (c.id.equals(sheng)) {
                                            shengshis += c.name
                                            shengshiIds += " " + c.id
                                        }
                                    }
                                    val shi = prov_id.substring(0, 4) + "00"
                                    for (c in it) {
                                        if (c.id.equals(shi)) {
                                            shengshis += c.name
                                            shengshiIds += " " + c.id
                                        }
                                    }
                                    for (c in it) {
                                        if (c.id.equals(prov_id)) {
                                            shengshis += c.name
                                            shengshiIds += " " + c.id
                                        }
                                    }
                                }

                                viewModel.qu.value = shengshis
                                viewModel.quIds.value = shengshiIds.trim()

                            }
                            it.get(0).bank_region_code?.let { area_id ->

                                var shengshis = ""
                                var shengshiIds = ""

                                citys?.RECORDS?.let {

                                    val sheng = area_id.substring(0, 2) + "0000"
                                    for (c in it) {
                                        if (c.id.equals(sheng)) {
                                            shengshis += c.name
                                            shengshiIds += " " + c.id
                                        }
                                    }
                                    val shi = area_id.substring(0, 4) + "00"
                                    for (c in it) {
                                        if (c.id.equals(shi)) {
                                            shengshis += c.name
                                            shengshiIds += " " + c.id
                                        }
                                    }
                                    for (c in it) {
                                        if (c.id.equals(area_id)) {
                                            shengshis += c.name
                                            shengshiIds += " " + c.id
                                        }
                                    }
                                }

                                viewModel.quBank.value = shengshis
                                viewModel.quIdsBank.value = shengshiIds.trim()

                            }

                        }
                    }


                    binding.emptyLayout.visibility = View.GONE
                } else {
                    toast(it.message)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })

        viewModel.callThree.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    toast("已提交")
                    finish()
                } else {
                    toast(it.message)
                }
            }
        })

        viewModel.idcardFont.observe(this, Observer {
            it?.let {
                binding.idcardFontImg.setImageBitmap(it)
            }
        })
        viewModel.idcardBack.observe(this, Observer {
            it?.let {
                binding.idcardBackImg.setImageBitmap(it)
            }
        })
        viewModel.callThree()

        viewModel.idcardFont.observe(this, Observer {
            it?.let {
                binding.idcardFontImg.setImageBitmap(it)
            }
        })
        viewModel.idcardBack.observe(this, Observer {
            it?.let {
                binding.idcardBackImg.setImageBitmap(it)
            }
        })
        viewModel.idcardFontHand.observe(this, Observer {
            it?.let {
                binding.idcardHandFontImg.setImageBitmap(it)
            }
        })
        viewModel.bankcardFont.observe(this, Observer {
            it?.let {
                binding.bankcardFontImg.setImageBitmap(it)
            }
        })
        viewModel.bandcardBack.observe(this, Observer {
            it?.let {
                binding.bankcardBackImg.setImageBitmap(it)
            }
        })
        viewModel.bandcardHand.observe(this, Observer {
            it?.let {
                binding.bankcardHandImg.setImageBitmap(it)
            }
        })
    }

    fun selectAddr() {

        val dialog = SelectAddrDialog(this)
        var one = ""
        var two = ""
        var three = ""
        if (!TextUtils.isEmpty(viewModel.qu.value)) {
            val qus = viewModel.qu.value!!.split(" ")
            qus?.let {
                if (qus.size >= 1)
                    one = qus[0]
                if (qus.size >= 2)
                    two = qus[1]
                if (qus.size >= 3)
                    three = qus[2]
            }
        }
        dialog.showDialog(one, two, three)
        dialog.onDismis { one, two, three ->
            viewModel.qu.value = "${one.name} ${two.name} ${three.name}"
            viewModel.quIds.value = "${one.id} ${two.id} ${three.id}"
        }
    }

    fun selectBankAddr() {

        val dialog = SelectAddrDialog(this)
        var one = ""
        var two = ""
        var three = ""
        if (!TextUtils.isEmpty(viewModel.quBank.value)) {
            val qus = viewModel.quBank.value!!.split(" ")
            qus?.let {
                if (qus.size >= 1)
                    one = qus[0]
                if (qus.size >= 2)
                    two = qus[1]
                if (qus.size >= 3)
                    three = qus[2]
            }
        }
        dialog.showDialog(one, two, three)
        dialog.onDismis { one, two, three ->

            viewModel.quBank.value = "${one.name} ${two.name} ${three.name}"
            viewModel.quIdsBank.value = "${one.id} ${two.id} ${three.id}"
        }
    }

    fun goTop() {
        SelectDateRangeDialog(this).apply {
            startDate = viewModel.startDate.value
            endDate = viewModel.endDate.value

            isLongDate.set(viewModel.id_card_type.value.equals("2"))
            selectCli = { s, e ->
                viewModel.startDate.value = s
                viewModel.endDate.value = e
            }
        }.show()
    }

    //身份证正面
    fun startIdCardFront() {

        OcrSDKKit.getInstance().startProcessOcrResultEntity(this@SetSkxxNewActivity,
            OcrType.IDCardOCR_FRONT,
            CustomConfigUi().apply {
                setLandscape(false)
            }, IdCardOcrResult::class.java,
            object : ISdkOcrEntityResultListener<IdCardOcrResult> {
                override fun onProcessSucceed(
                    idCardOcrResult: IdCardOcrResult,
                    ocrProcessResult: OcrProcessResult
                ) {
                    idCardOcrResult.getAddress()

                    // 更新图片
                    val bitmap: Bitmap? = base64ToBitmap(ocrProcessResult.getImageBase64Str())

                    viewModel.realName.value = idCardOcrResult.name
                    viewModel.idcard.value = idCardOcrResult.idNum
                    viewModel.userAddr.value = idCardOcrResult.address

                    viewModel.idcardFont.value = bitmap
                    viewModel.idcardFontUrl.value = ""
                }

                override fun onProcessFailed(
                    errorCode: String,
                    message: String,
                    ocrProcessResult: OcrProcessResult
                ) {
                    toast(message)
                    Log.e("requestId", ocrProcessResult.requestId)
                }
            })
    }

    // 身份证反面
    fun startIdCardBack() {
        OcrSDKKit.getInstance().startProcessOcr(this@SetSkxxNewActivity, OcrType.IDCardOCR_BACK,
            CustomConfigUi().apply {
                setLandscape(false)
            },
            object : ISDKKitResultListener {
                override fun onProcessSucceed(
                    response: String,
                    ocrProcessResult: OcrProcessResult
                ) {
                    val tempIdCardInfo: IdCardInfo =
                        Gson().fromJson(response, IdCardInfo::class.java)
                    Log.e("response", tempIdCardInfo.RequestId)

                    // 更新图片
                    val bitmap: Bitmap? = base64ToBitmap(ocrProcessResult.getImageBase64Str())
                    viewModel.idcardBack.value = bitmap
                    viewModel.idcardBackUrl.value = ""

//                    viewModel.idcardDate.value = tempIdCardInfo.ValidDate
                }

                override fun onProcessFailed(
                    errorCode: String,
                    message: String,
                    ocrProcessResult: OcrProcessResult
                ) {
                    toast(message)
                    Log.e("requestId", ocrProcessResult.getRequestId())
                }
            })
    }

    // 扫描银行卡
    fun startBankOcrPress() {
        // 更新临时密钥
        OcrSDKKit.getInstance()
            .startProcessOcrResultEntity(this@SetSkxxNewActivity, OcrType.BankCardOCR,
                CustomConfigUi().apply {
                    setLandscape(false)
                }, BankCardOcrResult::class.java,
                object : ISdkOcrEntityResultListener<BankCardOcrResult> {
                    override fun onProcessSucceed(
                        bankCardOcrResult: BankCardOcrResult,
                        ocrProcessResult: OcrProcessResult
                    ) {
                        Log.e(
                            "response",
                            bankCardOcrResult.toString() + " requestID:" + bankCardOcrResult.getRequestId()
                        )
                        // 更新图片
                        val bitmap: Bitmap? = base64ToBitmap(ocrProcessResult.getImageBase64Str())
                        viewModel.bankcardFont.value = bitmap
                        viewModel.bankcardFontUrl.value = ""

                        viewModel.bankCard.value = bankCardOcrResult.cardNo
                        viewModel.bankName.value = bankCardOcrResult.bankInfo

                        bankCardOcrResult.bankInfo.split("(")?.let {
                            if (it.size > 0) {
                                viewModel.bankName.value = it[0]
                            }
                        }
                    }

                    override fun onProcessFailed(
                        errorCode: String,
                        message: String,
                        ocrProcessResult: OcrProcessResult
                    ) {
                        toast(message)
                        Log.e("requestId", ocrProcessResult.getRequestId())
                    }
                })
    }

    fun base64ToBitmap(base64Data: String?): Bitmap? {
        val bytes = Base64.decode(base64Data, Base64.NO_WRAP)
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    }

    fun imgSelect(i: Int) { // 1 手持身份证正面，2手持身份证反面，3 手持银行卡正面 4银行卡反面

        CameraOrSelectDialog(this).apply {
            suc = {
                it?.let {
                    lifecycleScope.launch {
                        withContext(Dispatchers.IO) {
                            val file = Util.getLuBan(
                                this@SetSkxxNewActivity,
                                it
                            )
                            val b = BitmapFactory.decodeFile(file.absolutePath)
                            withContext(Dispatchers.Main) {
                                when (i) {
                                    1 -> {
                                        viewModel.idcardFontHand.value = b
                                        viewModel.idcardFontHandUrl.value = ""

                                    }

                                    2 -> {

                                    }

                                    3 -> {
                                        viewModel.bandcardHand.value = b
                                        viewModel.bandcardHandUrl.value = ""
                                        viewModel.bandcardHand2Url.value = ""

                                    }

                                    4 -> {
                                        viewModel.bandcardBack.value = b
                                        viewModel.bandcardBackUrl.value = ""

                                    }
                                }
                            }
                        }
                    }


                }

            }
        }.show()
    }

    fun ok() {
        if (viewModel.phone.value.isNullOrEmpty()) {
            toast("输入手机号")
            return
        }
        if (viewModel.realName.value.isNullOrEmpty()) {
            toast("输入姓名")
            return
        }
        if (viewModel.idcard.value.isNullOrEmpty()) {
            toast("输入身份证号")
            return
        }

        if (viewModel.startDate.value.isNullOrEmpty()) {
            toast("输入身份有效期")
            return
        }
        if (viewModel.quIds.value.isNullOrEmpty()) {
            toast("选择户籍省市区")
            return
        }
        if (viewModel.userAddr.value == null) {
            toast("输入用户详细地址")
            return
        }
        if (viewModel.userEmail.value == null) {
            toast("输入邮箱账号")
            return
        }
        if (viewModel.bankCard.value == null) {
            toast("输入银行卡号")
            return
        }
        if (viewModel.bankName.value == null) {
            toast("输入银行名称")
            return
        }
        if (viewModel.quIdsBank.value == null) {
            toast("选择开户银行省市区")
            return
        }
        if (viewModel.bankcardFont.value == null) {
            toast("选择银行卡卡号图片")
            return
        }
        if (viewModel.bandcardBack.value == null) {
            toast("选择银行卡磁条面图片")
            return
        }
        if (viewModel.bandcardHand.value == null) {
            toast("选择手持银行卡卡号面图片")
            return
        }
        if (viewModel.idcardFont.value == null) {
            toast("选择身份证人像面图片")
            return
        }
        if (viewModel.idcardBack.value == null) {
            toast("选择身份证国徽面图片")
            return
        }
        if (viewModel.idcardFontHand.value == null) {
            toast("选择手持身份证人像面")
            return
        }


        MsgTitleDialog(this).apply {
            okTxt = "提交"
            cancleTxt = "取消"
            title = "是否确定提交？"
            ok = {
                viewModel.ok(this@SetSkxxNewActivity)
            }
        }.show()


    }
}